package top.meeting.room.module.system.services.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Kv;
import top.meeting.room.common.config.MainConfig;
import top.meeting.room.common.kit.WxKit;
import top.meeting.room.module.system.form.RoleForm;

/**
 * Created by yunqisong on 2017/09/18.
 */
public class DepartmentService {
    public static final DepartmentService me = new DepartmentService();

    public static final Kv departments = Kv.create();

    private DepartmentService() {
    }

    private static final String allDepartment = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN";

    public JSONArray getAllDepartment() {
        JSONObject accessTokenJson = WxKit.getAccessToken(MainConfig.APP_ID, MainConfig.APP_SECRET);
        if (accessTokenJson != null) {
            String retVal = HttpKit.get(allDepartment.replaceFirst("ACCESS_TOKEN", accessTokenJson.getString("access_token")));
            JSONObject json = JSONObject.parseObject(retVal);
            JSONArray retJson = json.getJSONArray("department");
//            System.out.println(String.valueOf(retJson.toJSONString()));
            return (retJson != null && retJson.size() > 0) ? retJson : null;
        }
        return null;
    }


    public void fillDepartmentRole() {
        JSONArray depts = getAllDepartment();
        if (depts != null) {
            for (Object dept : depts) {
                JSONObject json = (JSONObject) dept;
                departments.set(json.getIntValue("id"), json.getString("name"));
                RoleService.me.saveDepartment(RoleForm.builder().roleName(json.getString("name")).build());
            }
        }
    }
}
